<template>
  <div class="p-2">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div class="search" v-show="showSearch">
        <el-form :model="queryParams" ref="queryFormRef" :inline="true" label-width="68px" class="search-form">
          <el-form-item label="服务名称" prop="serviceName">
            <el-input v-model="queryParams.serviceName" placeholder="请输入服务名称" clearable style="width: 240px" @keyup.enter="handleQuery" />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
            <el-button icon="Refresh" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>
      </div>
    </transition>

    <el-card shadow="never">
      <template #header>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" plain icon="Plus" @click="handleAdd" v-hasPermi="['office:serviceSetting:add']">新增</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate()" v-hasPermi="['office:serviceSetting:edit']"
              >编辑</el-button
            >
          </el-col>
          <el-col :span="1.5">
            <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete()" v-hasPermi="['office:serviceSetting:remove']"
              >删除</el-button
            >
          </el-col>
<!--          <el-col :span="1.5">-->
<!--            <el-button type="warning" plain icon="Download" @click="handleExport" v-hasPermi="['office:serviceSetting:export']">导出</el-button>-->
<!--          </el-col>-->
          <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>
      </template>

      <el-table
        height="calc(100vh - 370px)"
        v-loading="loading"
        :data="serviceSettingList"
        @selection-change="handleSelectionChange"
        @row-dblclick="(row: any, column: any, event: Event) => handleUpdate(row)"
      >
        <el-table-column label="序号" type="index" width="80" align="center" />
        <el-table-column label="服务名称" align="center" prop="serviceName" />
        <el-table-column label="服务功能" align="center" prop="featureIds">
          <template #default="scope">
            <dict-tag :options="service_function" :value="scope.row.featureIds" />
          </template>
        </el-table-column>
        <el-table-column label="服务价格" align="center" prop="servicePrice" />
        <el-table-column label="订阅时长" align="center" prop="subscribeDuration">
          <template #default="scope">
            <dict-tag :options="service_subscribe_duration" :value="scope.row.subscribeDuration" />
          </template>
        </el-table-column>
        <el-table-column label="启用状态" align="center" prop="enableStatus">
          <template #default="scope">
            <dict-tag :options="service_enable_status" :value="scope.row.enableStatus" />
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-button link type="primary" @click="handleUpdate(scope.row)" v-hasPermi="['office:serviceSetting:edit']">编辑</el-button>
            <el-button link type="primary" @click="switchEnableStatus(scope.row)" v-hasPermi="['office:serviceSetting:enableStatus']">
              {{ '0' === scope.row.enableStatus ? '启用' : '暂停' }}
            </el-button>
            <el-button link type="primary" @click="handleDelete(scope.row)" v-hasPermi="['office:serviceSetting:remove']">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <pagination v-show="total>0" :total="total" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" @pagination="getList" />
    </el-card>
    <!-- 添加或修改服务包设置对话框 -->
    <el-dialog :title="dialog.title" v-model="dialog.visible" width="750px" append-to-body>
      <el-form ref="serviceSettingFormRef" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="服务包名称" prop="serviceName">
          <el-input v-model="form.serviceName" placeholder="请输入服务名称" />
        </el-form-item>
        <el-form-item label="服务包描述" prop="serviceDesc">
          <el-input type="textarea" v-model="form.serviceDesc" placeholder="请输入服务描述" />
        </el-form-item>
        <el-row>
          <el-col :span="12">
            <el-form-item label="价格" prop="servicePrice">
              <el-input-number :precision="2" :controls="false" v-model="form.servicePrice" placeholder="请输入" style="padding-right: 10px;" /><span
                >元</span
              >
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="订阅时长" prop="subscribeDuration">
              <el-select v-model="form.subscribeDuration" placeholder="请选择订阅时长">
                <el-option v-for="dict in service_subscribe_duration" :key="dict.value" :label="dict.label" :value="dict.value"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="服务功能" prop="serviceFunction">
          <span style="color: red">说明：订阅的功能，会推送相关数据。</span>
          <el-table :data="functionData" style="width: 100%">
            <el-table-column label="序号" type="index" align="center" width="60" />
            <el-table-column label="功能名称" prop="label" width="100">
              <template #default="scope">
                {{ scope.row.label }}
              </template>
            </el-table-column>
            <el-table-column label="是否包含" prop="value" width="100">
              <template #default="scope">
                <el-checkbox v-model="scope.row.checked" />
              </template>
            </el-table-column>
            <el-table-column label="配置说明">
              <template #default="scope">
                <template v-if="scope.row.featureId === '2'">
                  <el-row style="padding-bottom: 10px">
                    <el-col :span="12">
                      <span>每次通话限制时长（分）</span>
                    </el-col>
                    <el-col :span="10">
                      <el-input-number v-model="scope.row.eachDuration" controls-position="right" />
                    </el-col>
                  </el-row>
                  <el-row style="padding-bottom: 10px">
                    <el-col :span="12">
                      <span>每月通话时长（分）</span>
                    </el-col>
                    <el-col :span="10">
                      <el-input-number v-model="scope.row.monthlyDuration" controls-position="right" />
                    </el-col>
                  </el-row>
                  <el-row style="padding-bottom: 10px">
                    <el-col :span="12">
                      <span>月底是否清零</span>
                    </el-col>
                    <el-col :span="10">
                      <el-radio-group v-model="scope.row.monthlyClearance" class="ml-4">
                        <el-radio :label="'0'">否</el-radio>
                        <el-radio :label="'1'">是</el-radio>
                      </el-radio-group>
                    </el-col>
                  </el-row>
                  <span style="color: #a77730">注：无设置，代表不限分钟。</span>
                </template>
              </template>
            </el-table-column>
          </el-table>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="ServiceSetting" lang="ts">
import {
  listServiceSetting,
  getServiceSetting,
  delServiceSetting,
  addServiceSetting,
  updateServiceSetting,
  switchStatus
} from '@/api/office/service/setting';
import { ServiceSettingVO, ServiceSettingQuery, ServiceSettingForm } from '@/api/office/service/setting/types';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { service_function, service_subscribe_duration, service_enable_status } = toRefs<any>(
  proxy?.useDict('service_function', 'service_subscribe_duration', 'service_enable_status')
);

const serviceSettingList = ref<ServiceSettingVO[]>([]);
const buttonLoading = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref<Array<string | number>>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const functionData = ref([]);
const queryFormRef = ref<ElFormInstance>();
const serviceSettingFormRef = ref<ElFormInstance>();

const dialog = reactive<DialogOption>({
  visible: false,
  title: ''
});

const initFormData: ServiceSettingForm = {
  id: undefined,
  serviceName: undefined,
  serviceDesc: undefined,
  servicePrice: undefined,
  subscribeDuration: undefined,
  serviceFunction: undefined,
  enableStatus: undefined
};
const data = reactive<PageData<ServiceSettingForm, ServiceSettingQuery>>({
  form: { ...initFormData },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    serviceName: undefined,
    serviceDesc: undefined,
    servicePrice: undefined,
    subscribeDuration: undefined,
    serviceFunction: undefined,
    enableStatus: undefined,
    params: {}
  },
  rules: {
    id: [{ required: true, message: '不能为空', trigger: 'blur' }],
    serviceName: [{ required: true, message: '服务名称不能为空', trigger: 'blur' }],
    servicePrice: [{ required: true, message: '服务价格不能为空', trigger: 'blur' }],
    subscribeDuration: [{ required: true, message: '订阅时长，单位：月不能为空', trigger: 'blur' }],
    serviceFunction: [{ message: '服务功能，json数组存储不能为空', trigger: 'change' }],
    enableStatus: [{ required: true, message: '启用状态：0、否；1、是不能为空', trigger: 'change' }]
  }
});

const { queryParams, form, rules } = toRefs(data);
/** 查询服务包设置列表 */
const getList = async () => {
  loading.value = true;
  const res = await listServiceSetting(queryParams.value);
  serviceSettingList.value = res.rows;
  total.value = res.total;
  loading.value = false;
};

/** 取消按钮 */
const cancel = () => {
  reset();
  dialog.visible = false;
};

/** 表单重置 */
const reset = () => {
  form.value = { ...initFormData };
  serviceSettingFormRef.value?.resetFields();
};

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
};

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  handleQuery();
};

/** 多选框选中数据 */
const handleSelectionChange = (selection: ServiceSettingVO[]) => {
  ids.value = selection.map((item) => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
};

/** 新增按钮操作 */
const handleAdd = () => {
  reset();
  functionData.value = service_function.value.map((e) => {
    return {
      featureId: e.value,
      label: e.label,
      checked: false
    };
  });
  dialog.visible = true;
  dialog.title = '添加服务包';
};

/** 修改按钮操作 */
const handleUpdate = async (row?: ServiceSettingVO) => {
  reset();
  const _id = row?.id || ids.value[0];
  const res = await getServiceSetting(_id);
  Object.assign(form.value, res.data);
  const functionDetails = form.value.functionDetails;
  functionData.value = service_function.value.map((e) => {
    let find = functionDetails.find((d) => d.featureId === e.value);
    if (find) {
      find.checked = true;
      find.label = e.label;
      return find;
    } else {
      return {
        featureId: e.value,
        label: e.label,
        checked: false
      };
    }
  });
  dialog.visible = true;
  dialog.title = '编辑服务包';
};

/** 提交按钮 */
const submitForm = () => {
  serviceSettingFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      buttonLoading.value = true;
      form.value.functionDetails = functionData.value.filter((e) => e.checked);
      if (form.value.id) {
        await updateServiceSetting(form.value).finally(() => (buttonLoading.value = false));
        proxy?.$modal.msgSuccess('修改成功');
      } else {
        await addServiceSetting(form.value).finally(() => (buttonLoading.value = false));
        proxy?.$modal.msgSuccess('新增成功');
      }
      dialog.visible = false;
      await getList();
    }
  });
};

const switchEnableStatus = async (row: ServiceSettingVO) => {
  await proxy?.$modal.confirm('0' === row.enableStatus ? '确认启用？' : '确认停用？').finally(() => (loading.value = false));
  await switchStatus(row.id, '0' === row.enableStatus ? '1' : '0');
  proxy?.$modal.msgSuccess('0' === row.enableStatus ? '启用成功' : '停用成功');
  await getList();
};

/** 删除按钮操作 */
const handleDelete = async (row?: ServiceSettingVO) => {
  const _ids = row ? [row.id] : ids.value;
  let msg = serviceSettingList.value
    .filter((e) => _ids.find((id) => e.id === id))
    .map((e) => e.serviceName)
    .join(',');
  await proxy?.$modal.confirm('是否确认删除服务包名称为"' + msg + '"的数据项？').finally(() => (loading.value = false));
  await delServiceSetting(_ids);
  proxy?.$modal.msgSuccess('删除成功');
  await getList();
};

/** 导出按钮操作 */
const handleExport = () => {
  proxy?.download(
    'office/serviceSetting/export',
    {
      ...queryParams.value
    },
    `serviceSetting_${new Date().getTime()}.xlsx`
  );
};

onMounted(() => {
  getList();
});
</script>
